package configuration

import (
	"fmt"
	"github.com/caarlos0/env/v6"
	"net/http"
	"time"
	server "v8s/http-server"
	"v8s/logger"
)

type (
	Properties struct {
		Log          logger.Properties           `envPrefix:"LOG_"`
		Kafka        KafkaProperties             `envPrefix:"MQ_"`
		APIServer    server.HttpServerProperties `envPrefix:"API_"`
		Management   server.HttpServerProperties `envPrefix:"MANAGEMENT_"`
		V8SApiClient HttpClientProperties        `envPrefix:"V8S_API_"`
	}

	HttpClientProperties struct {
		BaseUrl        string        `env:"BASE_URL,notEmpty"`
		RequestTimeout time.Duration `env:"REQUEST_TIMEOUT" envDefault:"180s"`

		TLS server.TLSProperties `envPrefix:"TLS_"`
	}

	KafkaProperties struct {
		RequestTopic  string   `env:"TOPIC_READ,notEmpty"`
		ResponseTopic string   `env:"TOPIC_WRITE,notEmpty"`
		GroupID       string   `env:"GROUP_ID,notEmpty"`
		Addresses     []string `env:"ADDRESS,notEmpty" envSeparator:","`
		Concurrency   int      `env:"CONCURRENCY" envDefault:"2"`

		TLS server.TLSProperties `envPrefix:"TLS"`
	}
)

func ReadProperties() *Properties {
	config := &Properties{}

	if err := env.Parse(config); err != nil {
		panic(fmt.Errorf("read config error: %w", err))
	}

	fmt.Printf("config: %+v", config)
	return config
}

func (properties *HttpClientProperties) GetClient() *http.Client {
	impl := &http.Client{}

	impl.Timeout = properties.RequestTimeout

	config, err := properties.TLS.ToConfig()
	if err != nil {
		panic(fmt.Errorf("cannot load server certificates pair: %w", err))
	}

	if config != nil {
		transport := http.DefaultTransport.(*http.Transport).Clone()
		transport.TLSClientConfig = config
		impl.Transport = transport
	}

	return impl
}
